﻿using System.Text.RegularExpressions;

namespace Jayden.Dll.Web
{
	public interface UriRewriter
	{
		Uri RewriteUri(Uri uri);
	}

	public class LangUriRewriter : UriRewriter
	{
		private string m_Lang;

		public LangUriRewriter(string lang) { m_Lang = lang; }

		public Uri RewriteUri(Uri uri)
		{
			string abs = uri.ToAbsoluteString(true);
			Uri newUri = null;
			if (abs.StartsWith("/" + m_Lang + "/"))
				newUri = new Uri(uri, abs.Substring(1 + m_Lang.Length), false);
			if (abs == "/" + m_Lang)
				newUri = new Uri(uri, "/", false);
			if (newUri != null)
				newUri["lang"] = m_Lang;
			return newUri ?? uri;
		}
	}

	public class RegexUriRewriter : UriRewriter
	{
		private Regex m_Regex;
		private Uri m_BaseUri;
		private string m_Path;

		public RegexUriRewriter(string pattern, string uri, string path)
		{
			m_Regex = new Regex(pattern, RegexOptions.CultureInvariant | RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase);
			if (uri != null)
				m_BaseUri = new Uri(uri, false);
			if (path != null)
				m_Path = path;
		}

		public Uri RewriteUri(Uri uri)
		{
			Match match = m_Regex.Match(uri.ToString(true));
			if (match.Success)
			{
				Uri clone = (m_BaseUri ?? uri).Clone() as Uri;
				if (m_Path != null)
					clone.AbsolutePath = m_Path;
				string[] groupNames = m_Regex.GetGroupNames();
				for (int c = 1; c < groupNames.Length; c++)
				{
					string groupName = groupNames[c];
					Group group = match.Groups[groupName];
					if (group != null)
						clone[groupName] = group.Value;
				}
				return clone;
			}
			return uri;
		}
	}
}
